<template>
  <div class="echart_bmap_wrapper">
    <div class="topBox">
      <div class="store" v-if="showStore">
        <el-select v-model="storeId" filterable placeholder="请选择" :popper-append-to-body="false" @change="changeStore">
          <el-option
            v-for="item in storeList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
      <div class="city">
        <div class="btn" type="primary" @click="goBack" size="mini">全国</div>
        <img src="../../assets/largeScreen/fullscreen.png" alt="" class="fullscreen-img" @click="amplify" v-if="typeInfo">
        <img src="../../assets/largeScreen/reduce.png" alt="" class="fullscreen-img" @click="reduce" v-if="!typeInfo">
      </div>
    </div>
    <div class="bmap-box" id="bmapChartBox"></div>
  </div>
</template>
<script>

import * as echarts from 'echarts';
var provinceMapData = require('@/utils/china.geo.json');//全国地图省份数据，自己取上面地址取
import axios from 'axios'//采用axios动态请求数据
import { vehicleMapInformation } from '../../api/largeScreen/index.js'
import {tenantStoreList} from '@/api/index';
export default {

  name: 'echartBmap',
  props: {
    mapChange: {
      type: Function,
      default: null
    },
    typeInfo: {
      type: Boolean,
      require: true
    },
    showStore: {
      type: Boolean,
      default:true
    },

  },
  data() {
    return {
      storeList: [],
      storeId: null,
      XY: [], // 点击区块的坐标
      type: true, // 放大还是缩小
      pointData: [],//标点信息，需要动态获取，初始化全国地图的点位
      provinceCodeData: [],//处理后全国省份数据带code
      mapStack: [],//存储一下地图历史记录，用于返回
      nowChooseData: [],//当前选择的数据源
      publicUrl: "https://geo.datav.aliyun.com/areas_v3/bound/",
      option: {
        tooltip: {},
        geo: [{
          map: 'js',
          aspectScale: 0.9,
          roam: true, // 是否允许缩放
          zoom: 3, // 默认显示级别
          center: [116.405285, 39.904989], // 地图中心点坐标
          label: {
            normal: {
              show: true, // 是否地图显示区域的文字，各省市的名字
              textStyle: {
                color: '#fff',
                fontSize: "14", //省份字体大小
              }
            },
            emphasis: {
              textStyle: {
                color: '#fff'
              }
            }
          },
          itemStyle: {
            // 区域颜色
            areaColor: {
              type: 'radial',
              x: 0.7,
              y: 0.5,
              r: 0.4,
              // 渐变效果
              colorStops: [{
                offset: 0,
                color: '#24cff4' // 0% 处的颜色
              }, {
                offset: 0.5,
                color: '#2babd9' // 50% 处的颜色
              }, {
                offset: 1,
                color: '#236bb2' // 100% 处的颜色
              }],
              global: false // 缺省为 false
            },
            emphasis: {
              areaColor: '#56dcf9', // 鼠标移入区域背景颜色
              borderWidth: 0
            },
            borderColor: '#37C1FD',
            borderWidth: 2
          },
          emphasis: {
            itemStyle: {
              areaColor: '#0160AD'
            },
            label: {
              show: 1,
              color: '#fff'
            }
          },
          zlevel: 3
        }],
        series: [{
          type: 'effectScatter',
          coordinateSystem: 'geo',
          // symbol: 'diamond',
          showEffectOn: 'render',
          rippleEffect: {
            period: 10,
            scale: 6,
            brushType: 'fill'
          },
          zlevel: 10, // 这里是关键，一定要放在 series中，显示层级，
          hoverAnimation: true,
          itemStyle: {
            normal: {
              // 点的颜色可以根据 params 参数里面的值去设定不通的颜色
              color: function (params) {
                if (params.name == '7300网关') {
                  return 'red';
                }
                if (params.name == '700网关') {
                  return 'yellow';
                }
                if (params.name == '5300网关') {
                  return 'green';
                } else {
                  return 'pink';
                }

              },
              shadowBlur: 10,
              shadowColor: '#333'
            }
          },
          data: [] // 点的数据，包含经纬度
        },
        {
          type: 'scatter',
          coordinateSystem: 'geo',
          //要有对应的经纬度才显示，先经度再维度
          data: [],
          showEffectOn: 'render',
          symbolSize: 30,
          label: {
            normal: {
              show: true,
              formatter: function (params) { //标签内容
                return params.name;
              },
              lineHeight: 15,
              backgroundColor: 'rgba(255,255,255,.9)',
              borderColor: '#80cffd',
              borderWidth: '1',
              padding: [2, 2, 2, 2],
              color: '#000000',
              fontSize: 10,
              borderRadius: '15',
              fontWeight: 'normal',
            },
            emphasis: {
              show: true
            }
          },
          itemStyle: {
            normal: {
              color: '#32cd32',
              shadowBlur: 10,
              shadowColor: '#333'
            }
          },
          emphasis: {
            itemStyle: {
              color: '#f4e925' // 高亮颜色
            }
          },
          zlevel: 10,
          symbol: 'image://' + require('../../assets/largeScreen/wiebao.png'),

        },
        {
          type: 'scatter',
          coordinateSystem: 'geo',
          //要有对应的经纬度才显示，先经度再维度
          data: [],
          showEffectOn: 'render',
          symbolSize: 30,
          label: {
            normal: {
              show: true,
              formatter: function (params) { //标签内容
                return params.name;
              },

            },
            emphasis: {
              show: true
            }
          },
          itemStyle: {
            normal: {
              color: '#32cd32',
              shadowBlur: 10,
              shadowColor: '#333'
            }
          },
          emphasis: {
            itemStyle: {
              color: '#f4e925' // 高亮颜色
            }
          },
          zlevel: 10,
          symbol: 'image://' + require('../../assets/largeScreen/gaojing.png'),

        },
        {
          type: 'scatter',
          coordinateSystem: 'geo',
          //要有对应的经纬度才显示，先经度再维度
          data: [],
          showEffectOn: 'render',
          symbolSize: 30,
          label: {
            normal: {
              show: true,
              formatter: function (params) { //标签内容
                return params.name;
              },

            },
            emphasis: {
              show: true
            }
          },
          itemStyle: {
            normal: {
              color: '#32cd32',
              shadowBlur: 10,
              shadowColor: '#333'
            }
          },
          emphasis: {
            itemStyle: {
              color: '#f4e925' // 高亮颜色
            }
          },
          zlevel: 10,
          symbol: 'image://' + require('../../assets/largeScreen/daoqi.png'),

        },
        {
          type: 'scatter',
          coordinateSystem: 'geo',
          //要有对应的经纬度才显示，先经度再维度
          data: [],
          showEffectOn: 'render',
          symbolSize: 30,
          label: {
            normal: {
              show: true,
              formatter: function (params) { //标签内容
                return params.name;
              },
            },
            emphasis: {
              show: false
            }
          },
          itemStyle: {
            normal: {
              color: '#32cd32',
              shadowBlur: 10,
              shadowColor: '#333'
            }
          },
          emphasis: {
            itemStyle: {
              color: '#f4e925' // 高亮颜色
            }
          },
          zlevel: 10,
          symbol: 'image://' + require('../../assets/largeScreen/store.png'),

        },
        ]
      },
      popShow: false,//弹窗是否显示
      popLeft: 0,//弹窗X轴距离
      popTop: 0,//弹窗Y轴距离
      name: '',//当前点击省份
      list1: [], // 正常车辆
      list2: [], // 维保车辆
      list3: [], // 到期车辆
      list4: [], // 告警车辆
      list5: [], // 门店信息
      allList: [], // 全部信息
    };
  },
  mounted() {
    this.tenantStoreList();
    this.getVehicleMapInformation()

    this.getProvinceCode();//处理全国省份数据
    // 初始化mapStack数据，默认全国数据
    this.mapStack = []
    this.mapStack.push(provinceMapData)
  },
  methods: {
    changeStore(){
      this.$emit('changeStoreSuccess', this.storeId);
      this.getVehicleMapInformation();
    },
    tenantStoreList() {
      tenantStoreList().then(res => {
        this.storeList = res.data;
        if(this.storeList.length > 0 && this.storeList.length==1){
          this.storeId = this.storeList[0].id;
          this.$emit('changeStoreSuccess', this.storeId);
          this.getVehicleMapInformation();
        }else  {
          const allObj = {
            id:null,
            name:'全部'
          }
          this.storeList.unshift(allObj);
        }
      })
    },
    // 获取车辆数据
    getVehicleMapInformation() {
      this.allList = []
      vehicleMapInformation({
        storeId:this.storeId
      }).then((res) => {
        if (res.code == 200) {

          if (res.data.ordinary && res.data.ordinary.length > 0) {
            res.data.ordinary.map((res) => {
              this.list1.push(res.coordinate)
            })
          }
          if (res.data.maintenance && res.data.maintenance.length > 0) {
            res.data.maintenance.map((res) => {
              this.list2.push(res.coordinate)
            })
          }
          if (res.data.insure && res.data.insure.length > 0) {
            res.data.insure.map((res) => {
              this.list3.push(res.coordinate)
            })
          }
          if (res.data.alarm && res.data.alarm.length > 0) {
            res.data.alarm.map((res) => {
              this.list4.push(res.coordinate)
            })
          }
          if (res.data.stores && res.data.stores.length > 0) {
            res.data.stores.map((res) => {
              this.list5.push(res.coordinate)
            })
          }
          this.allList = [...res.data.ordinary, ...res.data.maintenance, ...res.data.insure, ...res.data.alarm, ...res.data.stores]
          // 渲染地图
          this.drawMap(provinceMapData, 0, this.list1, this.list2, this.list3, this.list4, this.list5);

        }

      })
    },
    // 地图放大
    amplify() {
      this.mapChange(1, this.XY)

    },
    // 地图缩小
    reduce() {
      this.mapChange(2, this.XY)

    },
    // 处理全国省份数据
    getProvinceCode() {
      provinceMapData.features.forEach(item => {
        this.provinceCodeData.push({
          name: item.properties.name,
          coordinateCenter: item.properties.center,
          cityCode: item.properties.adcode
        })
      });
    },
    // 返回全国
    goBack() {
      this.popShow = false
      this.mapStack = []
      this.mapStack.push(provinceMapData)
      this.drawMap(provinceMapData, 0, this.list1, this.list2, this.list3, this.list4, this.list5);

    },
    // 设置地图配置信息
    setMapCenterZoomData(data, zoom, center, info, info1, info2) {
      var that = this
      console.log(that.list1)
      that.option.series[0].data = that.list1;
      that.option.series[1].data = that.list2;
      that.option.series[2].data = that.list3;
      that.option.series[3].data = that.list4;
      that.option.series[4].data = that.list5;
      that.option.geo[0].zoom = zoom;
      that.option.geo[0].center = center;

      let formt = {
        show: true,
        trigger: 'item',
        backgroundColor: 'transparent',
        padding: [0, 0, 0, 0],
        className: 'custom-tooltip',
        borderWidth: 0,
        formatter: function (params) {
          console.log(params);
          let carNo = ''
          let carStatus = ''
          let carInfo = ''
          let memberName = ''
          let contactPhone = ''
          let type = null
          let list = []
          that.allList.map((res) => {
            if (res.coordinate.toString() == params.value.toString()) {
              carNo = res.carNo == null ? '--' : res.carNo
              carStatus = res.carStatus == null ? '' : res.carStatus
              carInfo = res.carInfo == null ? '--' : res.carInfo
              memberName = res.memberName == null ? '--' : res.memberName
              contactPhone = res.contactPhone == null ? '--' : res.contactPhone
              type = res.type
              list = res.item
            }
          })
          let str1 = ''
          if (list) {
            list.map((res) => {
              if(res.type == 1) {
                str1 = `<div style='background: rgba(0,20,29,0.27);margin:5px 10px;text-align:center;border-radius:5px;width:210px;overflow:hidden'>${res.text}</div>${str1}`
              }else {
                str1 = `<div style='color:#4CFFF8;background: rgba(0,20,29,0.27);margin:5px 10px;text-align:center;border-radius:5px;width:210px;overflow:hidden'>${res.text}</div>${str1}`
              }

            })
          }
          console.log(str1)
          var str = `<div style = " color:#fff;background-color:none;position: relative;">
                          <img src='${require("../../assets/largeScreen/mapAleart.png")}' style="width:250px;min-height:250px;display: inline-block;position: absolute;top:0;left:0"></img>
                          <div style="width:250px;min-sheight:250px;padding:15px 10px;font-size:12px;position: absolute;top:0px;left:0;z-index:3">
                              <div style='margin:6px 10px 3px;text-align:center;font-size:14px'>
                                  <div style='float:left; color:#4CFFF8;font-weight: bold'>${carNo}</div>  
                                  <div style='float:right'>${carStatus}</div>
                              </div>
                              <div style='margin:3px 10px;margin-top:8px;width:210px;overflow:hidden;white-space: nowrap;
                            text-overflow: ellipsis;'>${carInfo}</div>
                              <div style='margin:3px 10px;'>姓名：${memberName}</div>
                              <div style='margin:3px 10px;'>手机号：${contactPhone}</div>
                              ${str1}
                          </div>

                      </div>`
          var str2 = `<div style = " color:#fff;background-color:none;position: relative;">
              <img src='${require("../../assets/largeScreen/mapAleart1.png")}' style="width:188px;min-height:108px;display: inline-block;position: absolute;top:0;left:0"></img>
              <div style="width:188px;min-sheight:108px;padding:15px 10px; font-size:14px;position: absolute;top:0px;left:0;z-index:3">
                  <div style='margin:3px 10px;color:#6EE8FF;font-weight: bold'>${carNo}</div>
                  <div style='margin:3px 10px;width:155px;white-space: break-spaces'>${carInfo}</div>
              </div>
          </div>`
          if (type == 5) {
            return str2
          } else {
            return str
          }

        }
      }
      that.option.tooltip = formt;
      if (that.mapStack.length <= 1) {//设置图层位置
        that.option.geo[0].layoutSize = '100%';
        that.option.geo[0].layoutCenter = ['85%', '20%'];
      } else {
        that.option.geo[0].layoutSize = '';
        that.option.geo[0].layoutCenter = [];
      }

    },
    // 渲染地图
    drawMap(json, type = 0, info1, info2, info3, info4, info5) {
      // 防止echarts重复
      if (document.getElementById('bmapChartBox') == null) {
        return
      }
      echarts.dispose(document.getElementById('bmapChartBox'))
      // 防止echarts重复

      this.echarts = echarts;
      this.dom = document.getElementById('bmapChartBox');
      this.myChart = this.echarts.init(this.dom);
      this.echarts.registerMap('js', json);

      if (type == 1) {//地图点击进入
        this.setMapCenterZoomData(info1, 1.2, info2,
          info3,
          info4, info5);
      } else {//初始化进入
        this.myChart.clear();
        this.setMapCenterZoomData(info1,
          1.3,
          [127.82862, 49.296976],
          info2,
          info3,
          info4,
          info5
        );
      }
      this.myChart.setOption(this.option);
      this.myChart.off('click');
      this.myChart.on('click', (param) => {

        // 点击弹窗方法
        // 点击获取经纬度
        let data = this.myChart.convertFromPixel('geo', [param.event.event.offsetX, param.event.event.offsetY])
        console.log(data, 111111111)
        this.XY = data
        this.popLeft = param.event.event.offsetX
        this.popTop = param.event.event.offsetY
        // 获取城市名称 list下的name值
        this.name = param.name
        this.popShow = true
        // 点击弹窗方法

        if (param.componentType == "geo") {//点击地图

        } else {//点击标点不允许下钻
          return;
        }
        // 省市区三级后跳出点击
        if (this.mapStack.length >= 3) {
          this.$notify({
            message: '没有更多啦！',
            type: 'warning',
            duration: 2000
          });
          return;
        }

        const city = param.name;
        // 获取点击对应的cityCode
        var cityCode = ''
        if (this.mapStack.length <= 1) {//初始化全国省份数据
          this.provinceCodeData.forEach(i => {
            if (i.name == city) {
              cityCode = i.cityCode
            }
          })
        } else {//选择后的市区数据
          this.nowChooseData.forEach(i => {
            if (i.name == city) {
              cityCode = i.cityCode
            }
          })
        }

        this.getHomeMapData(city, cityCode)
      });
    },
    // 获取基础配置数据
    getHomeMapData(city, cityCode) {
      let cityMapData //当前选中的省市区地图数据
      // 请求数据
      let data = cityCode + '_full.json'
      //通过接口获取点击下钻的地图数据
      axios.get(this.publicUrl + data).then(res => {
        if (res) {
          cityMapData = res.data
          // 让历史数据一直保持在3个之内，存储显示过的地图数据
          if (this.mapStack.length < 3) {
            this.mapStack.push(cityMapData);
          }
          this.nowChooseData = []
          cityMapData.features.forEach(item => {
            this.nowChooseData.push({
              name: item.properties.name,
              coordinateCenter: item.properties.center,
              cityCode: item.properties.adcode
            })
          });
          cityMapData && this.myChart.clear();
          cityMapData && this.drawMap(cityMapData, 1, city);
        }

      }).catch((err) => {
        this.getHomeMapNotFullData(city, cityCode)
        // this.$message(err.message);
      });
    },
    getHomeMapNotFullData(city, cityCode) {
      var cityMapData //当前选中的省市区地图数据
      // 请求数据

      var  data = cityCode+ '.json'
      //通过接口获取点击下钻的地图数据

      axios.get(this.publicUrl + data).then(res => {

        if (res) {
          cityMapData = res.data
          // 让历史数据一直保持在3个之内，存储显示过的地图数据
          if (this.mapStack.length < 3) {
            this.mapStack.push(cityMapData);
          }
          this.nowChooseData = []
          cityMapData.features.forEach(item => {
            this.nowChooseData.push({
              name: item.properties.name,
              coordinateCenter: item.properties.center,
              cityCode: item.properties.adcode
            })
          });
          cityMapData && this.myChart.clear();
          cityMapData && this.drawMap(cityMapData, 1, city);
        }

      }).catch((err) => {
        this.$message(err.message);
      });
    },


  }
};
</script>
<style lang="scss" scoped>
.fullscreen-img {
  width: 1.5vw;
  height: 1.5vw;
  //display: block;
  //position: absolute;
  //left: 15%;
  //top: 20px;
  cursor: pointer;
  z-index: 2;
}

.echart_bmap_wrapper {
  position: relative;
  .topBox{
    width: 100%;
    position: absolute;
    top:0;
    left: 0;
    display: flex;
    justify-content: space-between;
    padding: 2vh 6vh;
    z-index: 1;
    .store{
    }
    .city{
      display: flex;
      align-items: center;
      .btn {
        padding: 0.5vh 0.5vw;
        color: #C3CDE5;
        box-shadow: inset 0px 0px 11px 0px rgba(143, 239, 252, 0.5);
        border-radius: 3px;
        border: 1px solid #2EA8D0;
        cursor: pointer;
      }
    }
  }

  .bmap-box {
    width: 100%;
    height: 100%;
  }

  .popWin {
    position: absolute;
    left: 0;
    top: 0;
    background: #00305c;
    background-size: 100% 100%;
    width: 408px;
    height: 300px;
    z-index: 100;
    .popLine {
      width: 340px;
      height: 1px;
      background: linear-gradient(90deg, #FFFFFF 0%, rgba(255, 255, 255, 0) 100%);
      opacity: 0.3;
      margin-left: 30px;
    }

    .titleInfos {
      text-align: center;
      margin-left: 30px;
      font-size: 22px;
      font-family: YouSheBiaoTiHei;
      font-weight: 400;
      color: #00FDFE;
      height: 50px;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      flex-wrap: nowrap;
      flex-direction: row;
      align-content: flex-start;

      .pop_close {
        color: #bbb;
        cursor: pointer;
        padding: 5px;
        font-size: 12px;
        position: absolute;
        top: 5px;
        right: 10px;
      }
    }
  }

  .infoBody {
    width: 100%;
    padding: 3%;

    .homeTable {
      border: 1px solid #0376ae;
      border-radius: 10px;
    }
  }

  .infoBody ::v-deep .plTableBox .el-table .cell.el-tooltip {
    border-bottom: 1px solid #086896;
  }

  .infoBody ::v-deep .el-table,
  .el-table__expanded-cell {
    background-color: transparent;
  }

  .infoBody ::v-deep .el-table tr {
    // background-color: transparent!important;
    background-color: #0b4d73;
  }

  .infoBody ::v-deep .el-table--enable-row-transition .el-table__body td,
  .el-table .cell {
    background-color: transparent;
  }

  .el-table::before {
    //去除底部白线
    left: 0;
    bottom: 0;
    width: 100%;
    height: 0px;
  }

  .infoBody ::v-deep .plTableBox .el-table .el-table__header th {
    background-color: transparent;

  }

  .infoBody ::v-deep .plTableBox .el-table--enable-row-hover .el-table__body tr:hover>td {
    background-color: rgba(0, 77, 167, 1);
  }

  .infoBody ::v-deep .plTableBox .el-table--border td,
  .infoBody ::v-deep .plTableBox .el-table--border th,
  .infoBody ::v-deep .plTableBox .el-table__body-wrapper .el-table--border.is-scrolling-left~.el-table__fixed {
    border: none;
    color: #4daad3
  }

  .infoBody ::v-deep .plTableBox .el-table--medium td {
    padding: 0;
  }

  .infoBody ::v-deep .plTableBox .el-table__header-wrapper {
    background-color: transparent;
  }

  .infoBody ::v-deep .plTableBox .el-table--striped .el-table__body tr.el-table__row--striped td {
    background-color: #103c5c;
  }

  .store ::v-deep .el-input.el-input--suffix {
    // 2.修改背景颜色、字体颜色、边框、宽高
    .el-input__inner {
      color: #B1E2F6;
      height: 30px;
      width: 140px;
      background: rgba(7,50,69,0.23) !important;
      border-radius: 2px;
      border: 1px solid #53E8FF;
    }

    // 符号的位置会错乱，进行修正（水平）
    .el-input__suffix-inner {
      position: absolute;
      left: -25px;
    }

    // 符号的位置会错乱，进行修正（垂直）
    .el-select__caret.el-input__icon.el-icon-arrow-up {
      line-height: 30px;
    }

    .el-input__inner::placeholder {
      color: #fff;
    }

    .el-icon-arrow-up:before {
      color: #B1E2F6;
    }

  }

}

::v-deep .el-select-dropdown__wrap,
.el-scrollbar__wrap,
.el-scrollbar__wrap--hidden-default {
  border-radius: 2px;
  background-color: #0F3E66 !important;
  box-shadow: 0px 9px 28px 8px rgba(0,0,0,0.2), 0px 6px 16px 0px rgba(0,0,0,0.32), 0px 3px 6px -4px rgba(0,0,0,0.48);
  border: 0.5px solid #53E8FF;
}
::v-deep.el-select-dropdown__item{
  background-color: transparent;
  color: #B1E2F6;
}

::v-deep.el-select-dropdown__item:hover{
  background: rgba(255,255,255,0.06) !important;
}

::v-deep.el-popper .popper__arrow, .el-popper .popper__arrow::after{
  //display: none;
  background-color: #000 !important;
}
</style>
